package org.eyeTopLight.Filter;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import org.eyeTopLight.constant.ConstantUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.LinkedList;
import java.util.List;

/**
 * 在所有的请求前加过滤器进行token有效性的校验
 */
@Configuration
public class BaseFilter implements Filter {
    Logger logger = LoggerFactory.getLogger(BaseFilter.class);

    //白名单接口集合
    public static List<String> WHITE_PATH = new LinkedList<>();

    //jwt token的对称加密密钥
    private final static String SIGNING_KEY = "etl";

    @Value("${whiteList}")
    private String whiteList;


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        logger.info("初始化过滤器");
        String[] listOfWhiteList = whiteList.split(ConstantUtil.SEPARATOR_SYMBOL);
        for(String url : listOfWhiteList){
            WHITE_PATH.add(url);
        }
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//        HttpServletResponseWrapper wrapper = new HttpServletResponseWrapper((HttpServletResponse)servletResponse);
//        HttpServletRequest request = (HttpServletRequest) servletRequest;
//        String requestURI = request.getRequestURI();
//        if(WHITE_PATH.contains(requestURI)){
//            //白名单接口，直接通过
//            filterChain.doFilter(servletRequest,servletResponse);
//            return;
//        }
//        //进行校验，如token校验
//        String token = request.getHeader("Authorization");
//        if(token != null && jwtIsValid(token.substring(6,token.length()))){
//            filterChain.doFilter(servletRequest,servletResponse);
//        }else {
//            //token校验不通过，重定向到登录页面
//            wrapper.sendRedirect("/login/logout");
//        }
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {
    }

    /**
     * 对jwttoken进行校验，包括用户是否存在，时间是否到期
     * @param access_token
     * @return
     */
    public static boolean jwtIsValid(String access_token){
        try{
            Jws<Claims> jws = Jwts.parser()
                    .setSigningKey(SIGNING_KEY.getBytes(StandardCharsets.UTF_8))
                    .parseClaimsJws(access_token);
            int timeStamp = (int) jws.getBody().get("exp");
            long expireTime = ((long)timeStamp) * 1000;
            long curTimeStamp = System.currentTimeMillis();
            return curTimeStamp > expireTime ? false : true;
        }catch(Exception e){
            return false;
        }
    }
}
